package wang.jinggo.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

/**
 * DES工具类，CRM用户密码解密用
 * @author tanljs
 * @date 2018-03-27
 */
public class DESUtil {

    private AlgorithmParameterSpec iv = null;// 加密算法的参数接口，IvParameterSpec是它的一个实现
    private Key key = null;

    public String encode(String data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
        byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(pasByte);
    }

    public String decode(String data) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
        BASE64Decoder base64Decoder = new BASE64Decoder();

        byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));

        return new String(pasByte, "UTF-8");
    }

    private static String DecryptText(byte[] TextByte, String key) throws Exception {
        if (TextByte == null)
        {
            return "";
        }
        else if (TextByte.length <= 0)
        {
            return "";
        }

        DESKeySpec keySpec = new DESKeySpec(key.getBytes());    // 设置密钥参数
        AlgorithmParameterSpec iv2 = new IvParameterSpec(key.getBytes());// 设置向量
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
        Key key2 = keyFactory.generateSecret(keySpec);// 得到密钥对象

        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key2, iv2);

        byte[] pasByte = deCipher.doFinal(TextByte);

        String aa = new String(pasByte, "UTF-8");
        aa = aa.replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","");
        return aa;
    }

    public static String decryptSQLPWD(String sEncryedPWD)
    {
        if (sEncryedPWD.length() == 0 || !sEncryedPWD.contains("110ABCYYJ"))
        {
            return sEncryedPWD;
        }
        int startIndex = sEncryedPWD.indexOf("110ABCYYJ") + "110ABCYYJ".length();
        String sTmp = sEncryedPWD.substring(startIndex);
        sTmp = DecryptTextFromStr(sTmp, "DCDTCYYJ");
        return sTmp;
    }

    private static String DecryptTextFromStr(String text, String key) {
        try
        {
            int i;
            int k;
            byte[] arr = new byte[text.length() / 4];

            k = 0;
            String tt = "";
            for (i = 0; i < text.length(); i += 4)
            {
                String tr = text.substring(i, tt.length()  + 4);
                tt += tr;
                Integer tmpk = Integer.parseInt(tr);
                arr[k] = tmpk.byteValue();
                k += 1;
            }

            return DecryptText(arr, key);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return "";
        }
    }


    public static void main(String[] args) {
        try {
            String test = "a123456";
            String t2 = "110ABCYYJ0164009000940186007401570012025502120040022501790001003602110128";
            System.out.println("加密前的字符("+"a".getBytes()+")："+test);
//            System.out.println("加密后的字符："+des.encode(test));
//            System.out.println("解密后的字符："+des.decode(des.encode(test)));
            System.out.println("NEW解密后的字符："+decryptSQLPWD(t2));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
